import 'package:animated_transitions/animated_transitions.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:redux/redux.dart';
import '../../core/index.dart';
import '../../core/models/visitor_entity.dart';
import '../../core/store/redux_visitor_manager.dart';
import 'other_profile_page.dart';

/// 访客记录页面
class VamosVisitorRecordsInterface extends StatelessWidget {
  const VamosVisitorRecordsInterface({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage('assets/images/my_background.png'),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 标题栏
              _buildTitleBar(context),

              // 访客列表
              Expanded(child: _buildVisitorList()),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建标题栏
  Widget _buildTitleBar(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
      child: Row(
        children: [
          IconButton(
            onPressed: () => Navigator.pop(context),
            icon: Icon(Icons.arrow_back, color: Colors.white, size: 26.w),
          ),
          Expanded(
            child:
                Text(
                  'VISITOR RECORDS',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w700,
                    fontFamily:
                        GoogleFonts.goblinOne(
                          fontWeight: FontWeight.w700,
                        ).fontFamily,
                    letterSpacing: 1.2,
                  ),
                ).center(),
          ),
          SizedBox(width: 40.w), // 平衡左侧返回按钮
        ],
      ),
    );
  }

  /// 构建访客列表
  Widget _buildVisitorList() {
    return StoreConnector<AppState, List<VisitorWithUserData>>(
      converter: (store) {
        final currentUser = store.state.userState.activeUser;
        if (currentUser == null) return [];

        final visitorManager = serviceLocator<ReduxVisitorManager>();
        final userManager = serviceLocator<ReduxUserManager>();
        final visitors = visitorManager.getVisitorsSortedByTime(
          currentUser.uniqueId,
        );

        // 为每个访客添加用户数据
        return visitors.map((visitor) {
          final user = userManager.getUserById(visitor.visitorId);
          return VisitorWithUserData(visitor: visitor, user: user);
        }).toList();
      },
      builder: (context, visitorsWithData) {
        if (visitorsWithData.isEmpty) {
          return _buildEmptyState();
        }

        return ListView.builder(
          padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
          itemCount: visitorsWithData.length,
          itemBuilder: (context, index) {
            return _buildVisitorItem(context, visitorsWithData[index]);
          },
        );
      },
    );
  }

  /// 构建访客项
  Widget _buildVisitorItem(
    BuildContext context,
    VisitorWithUserData visitorData,
  ) {
    return Container(
      margin: EdgeInsets.only(bottom: 16.h),

      child: Row(
        children: [
          // 访客头像
          Container(
            width: 50.w,
            height: 50.w,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              border: Border.all(color: Color(0xFF404040), width: 1.w),
            ),
            child: ClipOval(
              child: Image.asset(
                visitorData.user?.profileImage ?? 'assets/images/avatar1.png',
                width: 50.w,
                height: 50.w,
                fit: BoxFit.cover,
                errorBuilder: (context, error, stackTrace) {
                  return Container(
                    color: Colors.grey[800],
                    child:
                        Icon(
                          Icons.person,
                          color: Colors.white,
                          size: 24.w,
                        ).center(),
                  );
                },
              ),
            ),
          ),

          SizedBox(width: 16.w),

          // 访客信息
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  visitorData.user?.displayName ?? 'Unknown User',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 16.sp,
                    fontWeight: FontWeight.w600,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w600,
                        ).fontFamily,
                  ),
                ),
                SizedBox(height: 4.h),
                Text(
                  _formatVisitTime(visitorData.visitor.visitTime),
                  style: TextStyle(
                    color: Colors.white.withOpacity(0.7),
                    fontSize: 12.sp,
                    fontFamily:
                        GoogleFonts.poppins(
                          fontWeight: FontWeight.w400,
                        ).fontFamily,
                  ),
                ),
              ],
            ),
          ),

          // 查看按钮
          Container(
            padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 8.h),
            decoration: BoxDecoration(
              color: Color(0x4CF0F0F0),
              borderRadius: BorderRadius.circular(20.r),
              border: Border.all(
                color: Colors.white.withOpacity(0.3),
                width: 1.w,
              ),
            ),
            child: Text(
              'View',
              style: TextStyle(
                color: Colors.white,
                fontSize: 12.sp,
                fontWeight: FontWeight.w500,
                fontFamily:
                    GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily,
              ),
            ),
          ).inkWell(
            onTap: () {
              _handleViewVisitor(context, visitorData.visitor);
            },
          ),
        ],
      ),
    );
  }

  /// 构建空状态
  Widget _buildEmptyState() {
    return Container(
      width: double.infinity,
      padding: EdgeInsets.symmetric(vertical: 60.h),
      child: Column(
        children: [
          Image.asset(
            'assets/images/empty.png',
            width: 80.w,
            height: 80.w,
            fit: BoxFit.contain,
          ),
          SizedBox(height: 16.h),
          Text('No visitors yet')
              .fontSize(16.sp)
              .textColor(Colors.white.withOpacity(0.7))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w500).fontFamily!,
              ),
          SizedBox(height: 8.h),
          Text('Your profile will appear here when someone visits')
              .fontSize(14.sp)
              .textColor(Colors.white.withOpacity(0.5))
              .fontFamily(
                GoogleFonts.poppins(fontWeight: FontWeight.w400).fontFamily!,
              ),
        ],
      ),
    );
  }

  /// 格式化访问时间
  String _formatVisitTime(DateTime visitTime) {
    final now = DateTime.now();
    final difference = now.difference(visitTime);

    if (difference.inDays > 0) {
      return '${difference.inDays} day${difference.inDays > 1 ? 's' : ''} ago';
    } else if (difference.inHours > 0) {
      return '${difference.inHours} hour${difference.inHours > 1 ? 's' : ''} ago';
    } else if (difference.inMinutes > 0) {
      return '${difference.inMinutes} minute${difference.inMinutes > 1 ? 's' : ''} ago';
    } else {
      return 'Just now';
    }
  }

  /// 处理查看访客
  void _handleViewVisitor(BuildContext context, VisitorEntity visitor) {
    // 获取访客的用户数据
    final userManager = serviceLocator<ReduxUserManager>();
    final visitorUser = userManager.getUserById(visitor.visitorId);

    if (visitorUser == null) {
      // 如果找不到用户数据，显示错误提示
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('User not found'),
          duration: Duration(seconds: 2),
        ),
      );
      return;
    }

    // 跳转到访客的主页
    Navigator.of(context).push(
      TransitionPageRoute(
        builder:
            (context) => StoreProvider<AppState>(
              store: serviceLocator<Store<AppState>>(),
              child: VamosOtherProfileInterface(user: visitorUser),
            ),
        transitionAnimation: BrushStrokeTransition(
          direction: TransitionDirection.right,
          colors: [Color(0xFF83BE4A), Color(0xFFF3E3C6), Color(0xFFFB894E)],
        ),
      ),
    );
  }
}

/// 访客数据与用户数据的组合类
class VisitorWithUserData {
  final VisitorEntity visitor;
  final UserDataEntity? user;

  VisitorWithUserData({required this.visitor, this.user});
}
